<template>
  <div class="bar" ref="boxRef" :style="{height: `${props.height}px`,width:`${props.width}px`}"></div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted,reactive, getCurrentInstance, ref } from 'vue'
import type { EChartsOption, EChartsType } from "echarts";
import * as echarts from "echarts";
const props:IProps = defineProps({
  height:{
    type:Number,
    default:300
  },
  width:{
    type:Number,
    default:300
  },
  title:{
    type:String,
  }
})
interface IProps{
    title?:string
    data?:{
        value:number;
        name:string;
    }[],
    height:number
    width:number   
}
const that = getCurrentInstance();
let chart:echarts.ECharts|null=null
onMounted(() => {
  let myChart = document.getElementsByClassName('bar')[0]
  // let Chart = that?.proxy?.$echarts.init(myChart as HTMLDivElement)
  chart = echarts.init(myChart as HTMLDivElement)
  chart.setOption(option)
})
onUnmounted(()=>{
  if(chart){
    chart.dispose()
    chart=null
  }
})
    // 使用防抖函数处理窗口大小变化事件
    function debounce(fn: Function, delay: number) {
      let timer: ReturnType<typeof setTimeout>
      return function(this: any, ...args: any[]) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn.apply(this, args)
        }, delay)
      }
    }
window.addEventListener('resize',debounce(()=>{
  if(chart){
    chart.resize()
  }
},200))

const option = reactive<EChartsOption>({
  title:{
    show: Boolean(`${props.title}` )|| false,
    text: props.title,
    textStyle: {
          color: '#333'
        }
  },
  
  legend: {},
  tooltip: {},
  dataset: {
    source: [
      ['product', '2015', '2016', '2017'],
      ['Matcha Latte', 43.3, 85.8, 93.7],
      ['Milk Tea', 83.1, 73.4, 55.1],
      ['Cheese Cocoa', 86.4, 65.2, 82.5],
      ['Walnut Brownie', 72.4, 53.9, 39.1]
    ]
  },
  xAxis: { type: 'category' },
  yAxis: {},
  // Declare several bar series, each will be mapped
  // to a column of dataset.source by default.
  series: [{ type: 'bar' }]

});
</script>
<style lang="scss" scoped></style>